import React, { useEffect, useState } from 'react'
import {
    Table, Pagination, Spin, Alert, Modal,
    Form,
    Input,
    Button,
    Row,
    Col,
    Space,
    Typography, Select, InputNumber, Empty
} from 'antd';
import backgroundImage from '../images/form_bg@2x.2d429e6ecd7d2c432e6f.png';
import {request} from "../utils/requset";
import { useSelector } from "react-redux";
import Jzpz from './Jzpz';


const backgroundStyle = {
    backgroundImage: `url(${backgroundImage})`,
    backgroundSize: 'cover', // 使背景图片覆盖整个容器
    backgroundPosition: 'center', // 背景图片居中
    backgroundRepeat: 'no-repeat', // 防止背景图片重复
    // minHeight: '100vh', // 确保背景图片覆盖整个视口高度
    // 其他您需要的样式
};


const { Title } = Typography;

const NwPzPage = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [clearLoading, setClearLoading] = useState(false);
    const [runLoading, setRunLoading] = useState(false);
    const [error, setError] = useState(false);
    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [dataSource, setDataSource] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中行的状态
    const [tableHeight, setTableHeight] = useState(500); // 默认高度
    const [visible, setVisible] = useState(false);
    const [modalContent, setModalContent] = useState('');
    const [fileLoading, setFileLoading] = useState(false);
    const [fyList, setFyList] = useState([]);
    const [fybhLoading, setFybhLoading] = useState(false)
    const [xhList, setXhList] = useState([]);
    const [xhLoading, setXhLoading] = useState(false)

    const sysConfig = useSelector(state => state.pz.sysConfig);


    const [searchParams, setSearchParams] = useState({
        year: ""
    });

    // 在组件挂载时获取数据
    useEffect(() => {
        fetchData(pageNum, pageSize);
    }, [sysConfig, pageNum, pageSize, searchParams]);


    // 动态设置表格高度
    useEffect(() => {
        const updateTableHeight = () => {
            const viewportHeight = window.innerHeight;
            const desiredHeight = viewportHeight / 2 - 50; // 例如，减去200像素用于其他内容
            setTableHeight(desiredHeight > 300 ? desiredHeight : 300); // 设置最小高度为300
        };

        updateTableHeight();
        window.addEventListener('resize', updateTableHeight);
        return () => window.removeEventListener('resize', updateTableHeight);
    }, []);

    useEffect(() => {
        fetchFyList();
        fetchXhList();
    }, [sysConfig])


    // 获取条件选项-费用
    const fetchFyList = async () => {
        setFybhLoading(true);
        setError(null);
        try {
            // console.log(values)
            // console.log(currentPage)
            // 替换为你的实际 API URL
            const response = await request.post('/nw_fymc/api/fylist', {
                "dwbh": sysConfig.dwbh,
                "model": sysConfig.model,
                "kjnd": sysConfig.kjnd
            }
            );

            const jsonData = response.data;
            setFyList(jsonData.data)
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setFybhLoading(false);
        }
    };

    // 获取条件选项-型号
    const fetchXhList = async () => {
        setXhLoading(true);
        setError(null);
        try {
            // console.log(values)
            // console.log(currentPage)
            // 替换为你的实际 API URL
            const response = await request.post('/nw_project/api/xhlist', {
                dwbh: sysConfig.dwbh,
                model: sysConfig.model,
                qzq_type: sysConfig.qzq_type,
                kjnd: sysConfig.kjnd
            }
            );

            const jsonData = response.data;
            setXhList(jsonData.data)
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setXhLoading(false);
        }
    };

    const [pzdata,setpzdata] = useState({})
    const NwPzColumns = [
        {
            title: 'UUID',
            dataIndex: 'uuid',
            key: 'uuid',
            hidden: true
        },
        {
            title: '单位编号',
            dataIndex: 'dwbh',
            key: 'dwbh',
            hidden: true
        },
        {
            title: '账套ID',
            dataIndex: 'ledger',
            key: 'ledger',
            hidden: true
        },
        {
            title: '会计年度',
            dataIndex: 'year',
            key: 'year',
            width: 100,
        },
        {
            title: '会计期间',
            dataIndex: 'kjqj',
            key: 'kjqj',
            width: 100,
        },
        {
            title: '凭证日期',
            dataIndex: 'pzrq',
            key: 'pzrq',
            width: 100,
        },
        {
            title: '凭证编号',
            dataIndex: 'pzbh',
            key: 'pzbh',
            width: 100,
            render: (dom, rowData, index) => (
                <a onClick={() => {
                    setisjzpz(true)
                    setpzdata(rowData)
                }}>{rowData['pzbh']}</a>
            ),
        },
        {
            title: '摘要',
            dataIndex: 'zy',
            key: 'zy',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '科目编号',
            dataIndex: 'kmbh',
            key: 'kmbh',
            width: 100,
        },
        {
            title: '科目名称',
            dataIndex: 'kmmc',
            key: 'kmmc',
            width: 120,
        },
        {
            title: '科目全称',
            dataIndex: 'kmqc',
            key: 'kmqc',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '金额',
            dataIndex: 'je',
            key: 'je',
            width: 100,
            align: 'right',
            render: (text) => <span>{parseFloat(text).toFixed(2)}</span>,

        },
        {
            dataIndex: 'jzfx',
            key: 'jzfx',
            hidden: true
        },
        {
            title: '记账方向',
            dataIndex: 'jzfx_zh',
            key: 'jzfx_zh',
            width: 100,
        },
        {
            title: '借方金额',
            dataIndex: 'jfje',
            key: 'jfje',
            width: 100,
            align: 'right',
            render: (text) => <span style={{ color: 'red' }}>{parseFloat(text).toFixed(2)}</span>,
        },
        {
            title: '贷方金额',
            dataIndex: 'dfje',
            key: 'dfje',
            width: 100,
            align: 'right',
            render: (text) => <span style={{ color: 'green' }}>{parseFloat(text).toFixed(2)}</span>,
        },
        {
            title: '记账否',
            dataIndex: 'jzf',
            key: 'jzf',
            width: 100,
            hidden: true,
        },
        {
            title: '往来单位编号',
            dataIndex: 'wldwbh',
            key: 'wldwbh',
            width: 160,
        },
        {
            title: '往来单位名称',
            dataIndex: 'wldwmc',
            key: 'wldwmc',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '主业项目编号',
            dataIndex: 'zx02bh',
            key: 'zx02bh',
            width: 160,
        },
        {
            title: '主业项目名称',
            dataIndex: 'zx02mc',
            key: 'zx02mc',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '主业项目全称',
            dataIndex: 'zx02qc',
            key: 'zx02qc',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '其他项目编号',
            dataIndex: 'zx99bh',
            key: 'zx99bh',
            width: 160,
        },
        {
            title: '其他项目名称',
            dataIndex: 'zx99mc',
            key: 'zx99mc',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
        {
            title: '其他项目全称',
            dataIndex: 'zx99qc',
            key: 'zx99qc',
            width: 200,
            render: (text) => (
                <span>
                    {text && text.length > 10 ? (
                        <>
                            {text.slice(0, 10)}...
                            <a onClick={() => handleShowModal(text)}>查看</a>
                        </>
                    ) : (
                        text
                    )}
                </span>
            ),
        },
    ];

    const handleShowModal = (text) => {
        setModalContent(text);
        setVisible(true);
    };
    // 获取表格数据的函数
    const fetchData = async (currentPage = 1, size = 10) => {
        setRunLoading(true);
        setError(null);
        try {
            // console.log(values)
            // console.log(currentPage)
            // 替换为你的实际 API URL
            const response = await request.post('/nw_pz/api/pagedata', {
                "dwbh": sysConfig.dwbh,
                "model": sysConfig.model,
                'qzq_type': sysConfig.qzq_type,
                "ledger": sysConfig.ledger,
                "pageNum": currentPage,
                "pageSize": size,
                "search": searchParams
            }
            );

            const jsonData = response.data;
            // console.log(jsonData)
            // 设置分页相关的状态
            // setPageCount(jsonData.pageCount);
            setPageNum(jsonData.pageNum);
            setPageSize(jsonData.pageSize);
            setTotal(jsonData.total);
            // setTotalPage(jsonData.totalPage);
            // console.log('length:'+jsonData.data.length)
            // 设置表格数据源
            setDataSource(jsonData.data);
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setRunLoading(false);
        }
    };

    const handleGetData = async () => {

        const values = await form.validateFields();

        setPageNum(1);
        setPageSize(10);
        setSearchParams({
            ...searchParams,
            ...values
        });
    }


    // 计算当前页显示的条数
    const startRow = (pageNum - 1) * pageSize + 1;
    const endRow = Math.min(pageNum * pageSize, total);
    // 页码变化时
    const onPageChange = (page, size) => {
        // console.log(page, size)
        setPageNum(page); // 设置当前页
        setPageSize(size); // 设置每页条数
    };

    const handleCancel = () => {
        setVisible(false);
    };


    const handleInputChange = (e) => {
        // console.log(e);
        setSearchParams({
            ...searchParams,
            [e.target.name]: e.target.value
        });
    };

    const handleFybhChange = (value) => {
        setSearchParams({
            ...searchParams,
            fybh: value
        });
    }

    const handleClearCondition = () => {
        setPageNum(1);
        setPageSize(10);
        setSearchParams({});
        form.resetFields()
    };
    const [isjzpz, setisjzpz] = useState(false)

    return (
        <>
            <Row justify="center">
                <Col xs={24} sm={20} md={24}>
                    <div className="config-page-layout float-center" style={backgroundStyle}>
                        <div className="upper-section">
                            <Title>
                                凭证查询
                                {/* 保存和运行按钮 */}
                                <Space className='float-right' style={{ marginBottom: 16, marginLeft: 8 }}>
                                    <Button type="primary" onClick={handleGetData} loading={runLoading}
                                        className='float-right'>
                                        查询
                                    </Button>
                                    <Button onClick={handleClearCondition} loading={runLoading}
                                        className='float-right'>
                                        清除条件
                                    </Button>
                                </Space>
                            </Title>

                            <Form
                                form={form}
                                layout="vertical"
                            >
                                <Row gutter={16}>
                                    <Col xs={24} sm={6} md={12}>
                                        <Form.Item
                                            label="摘要"
                                            name="zy"
                                        // onChange={handleInputChange}
                                        >
                                            <Input
                                                placeholder="摘要"
                                                value={searchParams.summary}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={4}>

                                        <Form.Item
                                            label="会计年度"
                                            name="year"
                                            // onChange={handleInputChange}
                                            rules={[{ pattern: /^[1-9]\d{3}$/, message: '请输入有效会计年度, 例如：2025 ' }]}
                                        >
                                            <Input
                                                placeholder="会计年度"
                                                value={searchParams.year}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={4}>
                                        <Form.Item
                                            label="会计期间"
                                            name="kjqj"
                                            // onChange={handleInputChange}
                                            rules={[{ pattern: /^(0[1-9]|1[0-2])$/, message: '请输入有效会计年度, 例如：02 ' }]}
                                        >
                                            {/*<Input*/}
                                            {/*    placeholder="会计期间"*/}
                                            {/*    value={searchParams.period}*/}
                                            {/*/>*/}
                                            <Select placeholder="会计期间"
                                                value={searchParams.period}
                                                options={[...Array(12)].map((_, index) => (
                                                    { label: (index + 1).toString().padStart(2, '0'), value: (index + 1).toString().padStart(2, '0') }
                                                ))} />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={4}>
                                        <Form.Item
                                            label="凭证编号"
                                            name="pzbh"
                                        // onChange={handleInputChange}
                                        >
                                            <Input
                                                placeholder="凭证编号"
                                                value={searchParams.voucher_number}
                                            />
                                        </Form.Item>
                                    </Col>
                                </Row>
                                <Row gutter={16}>
                                    <Col xs={24} sm={6} md={3}>
                                        <Form.Item
                                            label="金额"
                                            name="je_begin"
                                            // onChange={handleInputChange}
                                            rules={[{ type: 'number', message: '请输入有效数字' }]}
                                        >
                                            <InputNumber
                                                placeholder="金额"
                                                value={searchParams.summary}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={3}>
                                        <Form.Item
                                            label="至"
                                            name="je_end"
                                            // onChange={handleInputChange}
                                            rules={[{ type: 'number', message: '请输入有效数字' }]}
                                        >
                                            <InputNumber
                                                placeholder="至"
                                                value={searchParams.summary}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={4}>

                                        <Form.Item
                                            label="费用名称"
                                            name="fybh"
                                        >
                                            {/* 费用名称 */}
                                            <Select
                                                placeholder={fybhLoading ? "加载中..." : "请选择选项"}
                                                loading={fybhLoading}
                                                options={fyList.map((item) => ({ label: item.fybh + '-' + item.fymc, value: item.fybh }))}
                                            // initialValues={searchParams.fybh}
                                            >
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={4}>
                                        <Form.Item
                                            label="科目编号"
                                            name="kmbh"
                                        // onChange={handleInputChange}
                                        >
                                            <Input
                                                placeholder="科目编号"
                                                value={searchParams.account_number}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={4}>
                                        <Form.Item
                                            label="型号"
                                            name="code"
                                        // onChange={handleInputChange}
                                        >

                                            {/* 型号 */}
                                            <Select
                                                placeholder={xhLoading ? "加载中..." : "请选择选项"}
                                                loading={xhLoading}
                                                options={xhList.map((item) => ({ label: item.code + '-' + item.name, value: item.code }))}
                                            // initialValues={searchParams.code}
                                            >
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={6}>
                                        <Form.Item
                                            label="项目编号"
                                            name="xmbh"
                                        // onChange={handleInputChange}
                                        >
                                            <Input
                                                placeholder="项目编号"
                                                value={searchParams.project_number}
                                            />
                                        </Form.Item>
                                    </Col>
                                    {/*<Col>*/}
                                    {/*  <Button type="primary" onClick={handleGetData} loading={runLoading}>*/}
                                    {/*    搜索*/}
                                    {/*  </Button>*/}
                                    {/*</Col>*/}
                                </Row>

                            </Form>
                        </div>

                        {/* 下部分的表格 */}
                        <div className="lower-section">
                            <div className="my-data-table-container">
                                <Title level={4}>账务凭证明细</Title>
                                {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 16 }} />}

                                <Spin spinning={loading}>
                                    <Table
                                        size="small"
                                        columns={NwPzColumns}
                                        dataSource={dataSource}
                                        rowKey="uuid"
                                        pagination={false} // 使用自定义的分页组件
                                        scroll={{ x: 'max-content', y: tableHeight }} // 启用水平和垂直滚动
                                        rowClassName={(record) =>
                                            selectedRowKeys.includes(record.uuid) ? 'selected-row' : ''
                                        }
                                        locale={{ emptyText: <Empty description="未查询到数据"></Empty> }} // 自定义无数据时显示的文字
                                    />
                                    <Modal
                                        title="详情"
                                        open={visible}
                                        onCancel={handleCancel}
                                        footer={null}
                                    >
                                        <p>{modalContent}</p>
                                    </Modal>
                                </Spin>
                                <div>
                                    <span>
                                        当前 {startRow}-{endRow} 条，共 {total} 条
                                    </span>
                                    <Pagination
                                        current={pageNum}
                                        pageSize={pageSize}
                                        total={total}
                                        showSizeChanger
                                        pageSizeOptions={['10', '20', '50', '100']} // 限制每页条目数选项
                                        style={{ marginTop: 16, textAlign: 'right' }}
                                        onChange={onPageChange}      // 页码变化时触发
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </Col>
            </Row>
            {isjzpz && <Jzpz pzdata={pzdata} isjzpz={isjzpz} handleCancel={()=>setisjzpz(false)}/>}
        </>
    )
}

export default NwPzPage